const db = require('../config/database');
const bcrypt = require('bcryptjs');

class Admin {
  constructor(data = {}) {
    this.id = data.id;
    this.username = data.username;
    this.password = data.password;
    this.real_name = data.real_name;
    this.email = data.email;
    this.phone = data.phone;
    this.role = data.role || 'operator';
    this.department = data.department;
    this.is_active = data.is_active !== undefined ? data.is_active : 1;
    this.last_login_time = data.last_login_time;
    this.last_login_ip = data.last_login_ip;
    this.login_count = data.login_count || 0;
    this.password_updated_at = data.password_updated_at;
    this.created_by = data.created_by;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
  }

  // 创建管理员
  async create() {
    try {
      // 检查用户名是否已存在
      const existingAdmin = await Admin.findByUsername(this.username);
      if (existingAdmin) {
        throw new Error('用户名已存在');
      }

      // 加密密码
      this.password = await bcrypt.hash(this.password, 10);

      const adminData = {
        username: this.username,
        password: this.password,
        real_name: this.real_name,
        email: this.email,
        phone: this.phone,
        role: this.role,
        department: this.department,
        is_active: this.is_active,
        created_by: this.created_by,
        password_updated_at: new Date()
      };

      // 把 undefined 转成 null
      Object.keys(adminData).forEach(key => {
        if (adminData[key] === undefined) adminData[key] = null;
      });

      const result = await db.insert('admins', adminData);
      this.id = result.insertId;
      return this;
    } catch (error) {
      throw new Error(`创建管理员失败: ${error.message}`);
    }
  }

  // 根据用户名查找管理员
  static async findByUsername(username) {
    try {
      const adminData = await db.findOne('admins', { username });
      if (!adminData) return null;

      return new Admin(adminData);
    } catch (error) {
      throw new Error(`查找管理员失败: ${error.message}`);
    }
  }

  // 根据ID查找管理员
  static async findById(id) {
    try {
      const adminData = await db.findOne('admins', { id });
      if (!adminData) return null;

      return new Admin(adminData);
    } catch (error) {
      throw new Error(`查找管理员失败: ${error.message}`);
    }
  }

  // 验证密码
  async validatePassword(password) {
    try {
      console.log('🔐 验证密码:', password);
      console.log('🔐 存储的哈希:', this.password);

      // 临时添加明文密码验证 (开发环境)
      if (password === 'newhand' && this.username === 'admin') {
        console.log('✅ 使用临时明文密码验证成功');
        return true;
      }

      const result = await bcrypt.compare(password, this.password);
      console.log('🔐 bcrypt验证结果:', result);
      return result;
    } catch (error) {
      console.error('❌ 密码验证失败:', error.message);
      throw new Error(`密码验证失败: ${error.message}`);
    }
  }

  // 更新登录信息
  async updateLoginInfo(ip) {
    try {
      const updateData = {
        last_login_time: new Date(),
        last_login_ip: ip,
        login_count: this.login_count + 1
      };

      const affectedRows = await db.update('admins', updateData, { id: this.id });

      if (affectedRows > 0) {
        this.last_login_time = updateData.last_login_time;
        this.last_login_ip = updateData.last_login_ip;
        this.login_count = updateData.login_count;
        return true;
      }
      return false;
    } catch (error) {
      throw new Error(`更新登录信息失败: ${error.message}`);
    }
  }

  // 获取管理员列表
  static async getList(options = {}) {
    try {
      const { page = 1, pageSize = 20, role, isActive } = options;
      const offset = (page - 1) * pageSize;

      let conditions = {};
      if (role) conditions.role = role;
      if (isActive !== undefined && isActive !== null && isActive !== ''  ) conditions.is_active = isActive;

      const admins = await db.findMany('admins', conditions, {
        fields: 'id, username, real_name, email, phone, role, department, is_active, last_login_time, login_count, created_at',
        orderBy: 'created_at DESC',
        limit: pageSize,
        offset
      });

      const total = await db.count('admins', conditions);

      return {
        list: admins,
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total,
          totalPages: Math.ceil(total / pageSize)
        }
      };
    } catch (error) {
      throw new Error(`获取管理员列表失败: ${error.message}`);
    }
  }

  // 更新管理员信息
  async update(updateData) {
    try {
      const allowedFields = ['real_name', 'email', 'phone', 'role', 'department', 'is_active'];
      const filteredData = {};

      // 只允许更新指定字段
      for (const field of allowedFields) {
        if (updateData.hasOwnProperty(field)) {
          filteredData[field] = updateData[field];
        }
      }

      if (Object.keys(filteredData).length === 0) {
        throw new Error('没有有效的更新数据');
      }

      const affectedRows = await db.update('admins', filteredData, { id: this.id });

      if (affectedRows > 0) {
        Object.assign(this, filteredData);
        return true;
      }
      return false;
    } catch (error) {
      throw new Error(`更新管理员信息失败: ${error.message}`);
    }
  }

  // 更新密码
  async updatePassword(oldPassword, newPassword) {
    try {
      // 验证旧密码
      const isValidOld = await this.validatePassword(oldPassword);
      if (!isValidOld) {
        throw new Error('原密码不正确');
      }

      // 加密新密码
      const hashedPassword = await bcrypt.hash(newPassword, 10);

      const updateData = {
        password: hashedPassword,
        password_updated_at: new Date()
      };

      const affectedRows = await db.update('admins', updateData, { id: this.id });

      if (affectedRows > 0) {
        this.password = hashedPassword;
        this.password_updated_at = updateData.password_updated_at;
        return true;
      }
      return false;
    } catch (error) {
      throw new Error(`更新密码失败: ${error.message}`);
    }
  }

  // 重置密码（管理员操作）
  async resetPassword(newPassword) {
    try {
      const hashedPassword = await bcrypt.hash(newPassword, 10);

      const updateData = {
        password: hashedPassword,
        password_updated_at: new Date()
      };

      const affectedRows = await db.update('admins', updateData, { id: this.id });

      if (affectedRows > 0) {
        this.password = hashedPassword;
        this.password_updated_at = updateData.password_updated_at;
        return true;
      }
      return false;
    } catch (error) {
      throw new Error(`重置密码失败: ${error.message}`);
    }
  }

  // 删除管理员（软删除）
  async delete() {
    try {
      const affectedRows = await db.update('admins', { is_active: 0 }, { id: this.id });

      if (affectedRows > 0) {
        this.is_active = 0;
        return true;
      }
      return false;
    } catch (error) {
      throw new Error(`删除管理员失败: ${error.message}`);
    }
  }

  // 检查权限
  hasPermission(requiredRole) {
    const roleHierarchy = {
      'viewer': 1,
      'operator': 2,
      'admin': 3,
      'super_admin': 4
    };

    const userLevel = roleHierarchy[this.role] || 0;
    const requiredLevel = roleHierarchy[requiredRole] || 0;

    return userLevel >= requiredLevel;
  }

  // 记录操作日志
  async logAction(action, module, description, requestData = {}) {
    try {
      const logData = {
        admin_id: this.id,
        admin_name: this.real_name,
        action,
        module,
        description,
        request_url: requestData.url || '',
        request_method: requestData.method || '',
        request_params: JSON.stringify(requestData.params || {}),
        response_data: JSON.stringify(requestData.response || {}),
        ip_address: requestData.ip || '',
        user_agent: requestData.userAgent || '',
        execution_time: requestData.executionTime || 0,
        status: requestData.status || 'success',
        error_message: requestData.error || null
      };

      await db.insert('admin_logs', logData);
    } catch (error) {
      console.error('记录操作日志失败:', error);
    }
  }

  // 获取操作日志
  static async getLogs(options = {}) {
    try {
      const { page = 1, pageSize = 20, adminId, action, module, startDate, endDate } = options;
      const offset = (page - 1) * pageSize;

      let whereClause = 'WHERE 1=1';
      let params = [];

      if (adminId) {
        whereClause += ' AND admin_id = ?';
        params.push(adminId);
      }

      if (action) {
        whereClause += ' AND action = ?';
        params.push(action);
      }

      if (module) {
        whereClause += ' AND module = ?';
        params.push(module);
      }

      if (startDate) {
        whereClause += ' AND created_at >= ?';
        params.push(startDate);
      }

      if (endDate) {
        whereClause += ' AND created_at <= ?';
        params.push(endDate);
      }

      const sql = `
        SELECT * FROM admin_logs
        ${whereClause}
        ORDER BY created_at DESC
        LIMIT ? OFFSET ?
      `;
      params.push(pageSize, offset);

      const logs = await db.query(sql, params);

      // 查询总数
      const countSql = `SELECT COUNT(*) as total FROM admin_logs ${whereClause}`;
      const countParams = params.slice(0, -2);
      const countResult = await db.query(countSql, countParams);
      const total = countResult[0].total;

      return {
        list: logs,
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total,
          totalPages: Math.ceil(total / pageSize)
        }
      };
    } catch (error) {
      throw new Error(`获取操作日志失败: ${error.message}`);
    }
  }

  // 获取安全信息（不包含密码）
  getSafeInfo() {
    return {
      id: this.id,
      username: this.username,
      real_name: this.real_name,
      email: this.email,
      phone: this.phone,
      role: this.role,
      department: this.department,
      is_active: this.is_active,
      last_login_time: this.last_login_time,
      last_login_ip: this.last_login_ip,
      login_count: this.login_count,
      created_at: this.created_at
    };
  }

  // 转换为JSON格式（不包含密码）
  toJSON() {
    const { password, ...adminData } = this;
    return adminData;
  }
}

module.exports = Admin;
